package com.bitbits.plugins.settings;

import com.bitbits.plugins.components.Px2rpxComponent;
import com.bitbits.plugins.utils.LogicUtils;
import com.bitbits.plugins.utils.NumberUtils;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import static com.bitbits.plugins.Manifest.*;

import javax.swing.*;
import java.util.Objects;

/**
 * px2rpx设置项
 */
public class Px2rpxSettingsConfigurable implements SearchableConfigurable {
    // 插件配置状态机
    Px2rpxSettings settings;
    // 插件配置页面
    Px2rpxComponent component;

    public Px2rpxSettingsConfigurable() {
        this.settings = Px2rpxSettings.getInstance();
    }

    /**
     * 获取插件配置页面组件
     * @return 配置页组件
     */
    @Override
    @Nullable
    public JComponent createComponent() {
        this.component = new Px2rpxComponent(this.settings);
        return this.component.$$$getRootComponent$$$();
    }

    /**
     * 应用插件配置
     */
    @Override
    public void apply() throws ConfigurationException {
        LogicUtils.getLogic().conOrEnd(
                this.component.getIptDesignWidth().getText(),
                text -> Objects.nonNull(text) && NumberUtils.isCreatable(text) && NumberUtils.toInt(text) > 0,
                text -> this.settings.setDesignWidth(NumberUtils.toInt(text))
        );
    }

    /**
     * 重置插件配置
     */
    @Override
    public void reset() {
        this.component.getIptDesignWidth().setText(this.settings.designWidth.toString());
    }

    /**
     * 插件id搜索
     * @return 插件id
     */
    @Override
    @NotNull
    public String getId() {
        return PLUGIN_NAME;
    }

    /**
     * 插件名字搜索
     * @return 插件名
     */
    @Override
    public String getDisplayName() {
        return PLUGIN_SETTINGS_DISPLAY_NAME;
    }

    /**
     * 配置是否修改
     * @return 是否已修改
     */
    @Override
    public boolean isModified() {
        Px2rpxSettings set = Px2rpxSettings.getInstance();
        return !this.component.getIptDesignWidth().getText().equals(set.designWidth.toString());
    }
}
